<template>
  <div class="production-order-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Tickets /></el-icon>
          <span>生产工单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" class="filter-form" inline @keyup.enter="handleSearch">
        <el-form-item>
          <el-input
            v-model="searchForm.workOrderCodeOrName"
            placeholder="请输入工单编号/名称"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchForm.planNameOrCode"
            placeholder="请输入计划名称/编号"
            clearable
            class="w-220"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchForm.productName"
            placeholder="请选择产品名称"
            clearable
            filterable
            class="w-180"
          >
            <el-option
              v-for="option in productOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable class="w-180">
            <el-option label="待排产" :value="0" />
            <el-option label="未开始" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已关闭" :value="4" />
            <el-option label="已暂停" :value="5" />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <div class="toolbar">
        <el-button type="primary" @click="handleSchedule">排产</el-button>
        <el-button type="success" @click="handleStart">开始</el-button>
        <el-button type="warning" plain @click="handleCancel">取消</el-button>
        <el-button type="primary" plain @click="handleEnd">结束</el-button>
        <el-button type="danger" plain @click="handleRecall">撤回</el-button>
      </div>

      <el-table
        :data="rows"
        border
        stripe
        :loading="loading"
        height="640"
        class="order-table"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="productName" label="产品名称" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.productName) }}
          </template>
        </el-table-column>
        <el-table-column prop="specModel" label="规格型号" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.specModel) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderCode" label="工单编号" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.orderCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderName" label="工单名称" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.orderName) }}
          </template>
        </el-table-column>
        <el-table-column prop="planName" label="关联计划" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.planName) }}
          </template>
        </el-table-column>
        <el-table-column prop="planCode" label="计划编号" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.planCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="产品编号" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.productCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="productType" label="产品类型" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            {{ formatEmpty(scope.row.productType) }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center">
          <template #default="scope">
            {{ formatEmpty(scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column label="计划数量" width="100" align="center">
          <template #default="scope">
            {{ scope.row.planQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="实际数量" width="100" align="center">
          <template #default="scope">
            {{ scope.row.actualQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="需求日期" min-width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.demandDate) }}
          </template>
        </el-table-column>
        <el-table-column label="计划开工时间" min-width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.planStartTime) }}
          </template>
        </el-table-column>
        <el-table-column label="计划完工时间" min-width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.planFinishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="实际开工时间" min-width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.actualStartTime) }}
          </template>
        </el-table-column>
        <el-table-column label="实际完工时间" min-width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.actualFinishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="工单进度" min-width="180">
          <template #default="scope">
            <el-progress 
              :percentage="getProgressPercentage(scope.row)" 
              :status="progressStatus(scope.row)" 
            />
            <div class="progress-desc">合格/计划：{{ scope.row.actualQuantity || 0 }}/{{ scope.row.planQuantity || 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center" fixed="right">
          <template #default="scope">
            <el-tag :type="statusTagType(getStatusNumber(scope.row.status))" size="small">
              {{ statusName(getStatusNumber(scope.row.status)) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right" align="center">
          <template #default="scope">
            <el-button
              v-if="getStatusNumber(scope.row.status) === 0"
              type="primary"
              link
              size="small"
              @click="handleScheduleRow(scope.row)"
            >
              排产
            </el-button>
            <el-button type="primary" link size="small" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-12 flex-end">
        <el-pagination
          v-model:current-page="pager.page"
          v-model:page-size="pager.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager.total"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, HomeFilled, Setting, Tickets } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

// 生产工单列表项接口
interface ProductionOrderItem {
  id: number
  orderCode: string
  orderName: string
  planId?: number
  planCode?: string
  planName: string
  productName: string
  productCode: string
  specModel?: string
  productType?: string
  unit?: string
  demandDate?: string
  planQuantity: number
  actualQuantity: number
  planStartTime?: string
  planFinishTime?: string
  actualStartTime?: string
  actualFinishTime?: string
  status: number | string
  progress?: {
    prepare: number
    execute: number
    quality: number
    done: number
  }
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number
  msg: string
  data: T[]
  totalCount: number
  pageCount: number
}

const router = useRouter()

const loading = ref(false)
const allOrders = ref<ProductionOrderItem[]>([])
const rows = ref<ProductionOrderItem[]>([])
const multipleSelection = ref<ProductionOrderItem[]>([])

const pager = reactive({
  page: 1,
  size: 10,
  total: 0
})

const searchForm = reactive({
  workOrderCodeOrName: '',
  planNameOrCode: '',
  productName: '',
  status: undefined as number | undefined
})

const productOptions = computed(() => {
  const set = new Set(rows.value.map((item: ProductionOrderItem) => item.productName).filter(Boolean))
  return Array.from(set).sort()
})

// 格式化空值显示
const formatEmpty = (value: string | undefined | null): string => {
  if (!value || value === '' || value === 'null' || value === 'undefined') {
    return '-'
  }
  return String(value)
}

// 格式化日期
const formatDate = (value?: string | Date | null): string => {
  if (!value) return '-'
  try {
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) {
      return '-'
    }
    const pad = (num: number) => `${num}`.padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
  } catch {
    return '-'
  }
}

// 格式化日期时间
const formatDateTime = (value?: string | Date | null): string => {
  if (!value) return '-'
  try {
    const date = new Date(value)
    if (Number.isNaN(date.getTime())) {
      return '-'
    }
    const pad = (num: number) => `${num}`.padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
  } catch {
    return '-'
  }
}

// 获取进度百分比
const getProgressPercentage = (row: ProductionOrderItem): number => {
  if (row.progress) {
    return Math.round(row.progress.done || 0)
  }
  if (row.planQuantity > 0 && row.actualQuantity > 0) {
    return Math.round((row.actualQuantity / row.planQuantity) * 100)
  }
  return 0
}

// 获取状态数字
const getStatusNumber = (status: number | string): number => {
  if (typeof status === 'number') {
    return status
  }
  const statusMap: Record<string, number> = {
    '待排产': 0,
    '未开始': 1,
    '进行中': 2,
    '已完成': 3,
    '已关闭': 4,
    '已暂停': 5
  }
  return statusMap[status] ?? 0
}

// 从API获取生产工单列表
const fetchListFromAPI = async () => {
  loading.value = true
  try {
    const response = await https.Reads.get('/AProduction_Work_Order/GetWorkOrderPage', {
      params: {
        taskKeyword: searchForm.workOrderCodeOrName || undefined,
        planKeyword: searchForm.planNameOrCode || undefined,
        productName: searchForm.productName || undefined,
        status: searchForm.status || undefined,
        pageIndex: pager.page,
        pageSize: pager.size
      }
    })
    const payload = extractPayload(response)
    if (isRequestSuccess(payload) && Array.isArray(payload?.data ?? payload?.Data)) {
      const apiData = payload?.data ?? payload?.Data ?? []
      // 转换API数据格式为前端需要的格式
      const apiOrders = apiData.map((item: any) => ({
        id: item.id || item.Id || 0,
        orderCode: item.orderCode || item.OrderCode || item.workOrderCode || item.WorkOrderCode || '',
        orderName: item.orderName || item.OrderName || item.workOrderName || item.WorkOrderName || '',
        planId: item.planId || item.PlanId,
        planCode: item.planCode || item.PlanCode || '',
        planName: item.planName || item.PlanName || '',
        productName: item.productName || item.ProductName || '',
        productCode: item.productCode || item.ProductCode || '',
        specModel: item.specModel || item.SpecModel || item.productModel || item.ProductModel || '',
        productType: item.productType || item.ProductType || '',
        unit: item.unit || item.Unit || item.productUnit || item.ProductUnit || '',
        demandDate: item.demandDate || item.DemandDate || '',
        planQuantity: item.planQuantity || item.PlanQuantity || 0,
        actualQuantity: item.actualQuantity || item.ActualQuantity || 0,
        planStartTime: item.planStartTime || item.PlanStartTime || '',
        planFinishTime: item.planFinishTime || item.PlanFinishTime || '',
        actualStartTime: item.actualStartTime || item.ActualStartTime || '',
        actualFinishTime: item.actualFinishTime || item.ActualFinishTime || '',
        status: item.status || item.Status || '待排产',
        progress: {
          prepare: item.progress?.prepare || item.Progress?.prepare || 0,
          execute: item.progress?.execute || item.Progress?.execute || 0,
          quality: item.progress?.quality || item.Progress?.quality || 0,
          done: item.progress?.done || item.Progress?.done || 0
        }
      }))
      
      // 合并本地存储的工单
      const localOrders = loadOrdersFromLocalStorage()
      if (localOrders.length > 0) {
        const apiOrderCodes = new Set(apiOrders.map((o: ProductionOrderItem) => o.orderCode))
        const uniqueLocalOrders = localOrders.filter((o: ProductionOrderItem) => o.orderCode && !apiOrderCodes.has(o.orderCode))
        allOrders.value = [...apiOrders, ...uniqueLocalOrders]
      } else {
        allOrders.value = apiOrders
      }
      
      pager.total = payload?.totalCount ?? payload?.TotalCount ?? allOrders.value.length
      applyFilters()
    } else {
      // API失败时从本地存储加载
      console.warn('获取生产工单API失败，从本地存储加载')
      const localOrders = loadOrdersFromLocalStorage()
      if (localOrders.length > 0) {
        allOrders.value = localOrders
        applyFilters()
      } else {
        allOrders.value = []
        pager.total = 0
        rows.value = []
      }
    }
  } catch (error) {
    console.warn('获取生产工单失败，从本地存储加载:', error)
    const localOrders = loadOrdersFromLocalStorage()
    if (localOrders.length > 0) {
      allOrders.value = localOrders
      applyFilters()
    } else {
      allOrders.value = []
      pager.total = 0
      rows.value = []
    }
  } finally {
    loading.value = false
  }
}

// 从本地存储获取工单
const loadOrdersFromLocalStorage = (): ProductionOrderItem[] => {
  try {
    const stored = localStorage.getItem('production_work_orders')
    if (stored) {
      const parsed = JSON.parse(stored) as ProductionOrderItem[]
      return parsed.filter(item => item && item.orderCode) // 过滤无效数据
    }
  } catch (error) {
    console.error('从本地存储加载工单失败:', error)
  }
  return []
}

// 保存工单到本地存储
const saveOrdersToLocalStorage = (orders: ProductionOrderItem[]) => {
  try {
    localStorage.setItem('production_work_orders', JSON.stringify(orders))
  } catch (error) {
    console.error('保存工单到本地存储失败:', error)
  }
}

// 应用筛选条件
const applyFilters = () => {
  let filteredData = [...allOrders.value]
  
  // 工单编号/名称筛选
  if (searchForm.workOrderCodeOrName) {
    const keyword = searchForm.workOrderCodeOrName.toLowerCase()
    filteredData = filteredData.filter((item: ProductionOrderItem) => 
      (item.orderCode || '').toLowerCase().includes(keyword) || 
      (item.orderName || '').toLowerCase().includes(keyword)
    )
  }
  
  // 计划名称/编号筛选
  if (searchForm.planNameOrCode) {
    const keyword = searchForm.planNameOrCode.toLowerCase()
    filteredData = filteredData.filter((item: ProductionOrderItem) => 
      (item.planCode || '').toLowerCase().includes(keyword) || 
      (item.planName || '').toLowerCase().includes(keyword)
    )
  }
  
  // 产品名称筛选
  if (searchForm.productName) {
    filteredData = filteredData.filter((item: ProductionOrderItem) => item.productName === searchForm.productName)
  }
  
  // 状态筛选
  if (searchForm.status !== undefined) {
    filteredData = filteredData.filter((item: ProductionOrderItem) => {
      const itemStatus = getStatusNumber(item.status)
      return itemStatus === searchForm.status
    })
  }
  
  // 分页
  const start = (pager.page - 1) * pager.size
  const end = start + pager.size
  rows.value = filteredData.slice(start, end)
  pager.total = filteredData.length
}

const fetchList = async () => {
  await fetchListFromAPI()
}

const handleSearch = () => {
  pager.page = 1
  fetchList()
}

const handleReset = () => {
  searchForm.workOrderCodeOrName = ''
  searchForm.planNameOrCode = ''
  searchForm.productName = ''
  searchForm.status = undefined
  pager.page = 1
  fetchList()
}

const onSelectionChange = (val: ProductionOrderItem[]) => {
  multipleSelection.value = val
}

const onPageSizeChange = (size: number) => {
  pager.size = size
  pager.page = 1
  applyFilters()
}

const onPageChange = (page: number) => {
  pager.page = page
  applyFilters()
}

const handleSchedule = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择需要排产的工单')
    return
  }
  if (multipleSelection.value.length > 1) {
    ElMessage.warning('请一次只选择一个工单进行排产')
    return
  }
  handleScheduleRow(multipleSelection.value[0]!)
}

const handleScheduleRow = (row: ProductionOrderItem) => {
  router.push({ path: '/WorkOrderSchedule', query: { id: row.id } })
}

const handleStart = () => {
  ElMessage.info('开始功能开发中')
}

const handleCancel = () => {
  ElMessage.info('取消功能开发中')
}

const handleEnd = () => {
  ElMessage.info('结束功能开发中')
}

const handleRecall = () => {
  ElMessage.info('撤回功能开发中')
}

const handleView = (row: ProductionOrderItem) => {
  router.push({ path: '/WorkOrderDetail', query: { id: row.id } })
}

const statusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'info'
    case 2:
      return 'success'
    case 3:
      return 'success'
    case 4:
      return 'danger'
    case 5:
      return 'info'
    default:
      return 'info'
  }
}

const statusName = (status: number) => {
  const names: Record<number, string> = {
    0: '待排产',
    1: '未开始',
    2: '进行中',
    3: '已完成',
    4: '已关闭',
    5: '已暂停'
  }
  return names[status] ?? '未知'
}

const progressStatus = (row: ProductionOrderItem) => {
  const status = getStatusNumber(row.status)
  if (status === 3) return 'success'
  if (status === 2) return ''
  return 'exception'
}

// 添加工单到列表（供外部调用）
const addWorkOrders = (newOrders: ProductionOrderItem[]) => {
  const ordersWithId = newOrders.map((order, index) => ({
    ...order,
    id: order.id || Date.now() + index,
    actualQuantity: order.actualQuantity || 0,
    actualStartTime: order.actualStartTime || '',
    actualFinishTime: order.actualFinishTime || '',
    progress: order.progress || {
      prepare: 0,
      execute: 0,
      quality: 0,
      done: 0
    }
  }))
  
  allOrders.value = [...ordersWithId, ...allOrders.value]
  saveOrdersToLocalStorage(allOrders.value)
  applyFilters()
  
  ElMessage.success(`成功添加 ${ordersWithId.length} 个生产工单`)
}

// 暴露方法供外部调用
defineExpose({
  addWorkOrders,
  fetchList
})

// 监听工单更新事件
const handleWorkOrdersUpdated = (event: CustomEvent) => {
  const newOrders = event.detail as ProductionOrderItem[]
  if (newOrders && newOrders.length > 0) {
    addWorkOrders(newOrders)
  }
}

onMounted(() => {
  fetchList()
  window.addEventListener('workOrdersUpdated', handleWorkOrdersUpdated as EventListener)
})

onUnmounted(() => {
  window.removeEventListener('workOrdersUpdated', handleWorkOrdersUpdated as EventListener)
})
</script>

<style scoped>
.production-order-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.filter-card,
.table-card {
  margin-bottom: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.order-table {
  width: 100%;
}

.progress-desc {
  margin-top: 6px;
  font-size: 12px;
  color: #8c98b0;
}

.mt-12 {
  margin-top: 12px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
}

.w-180 {
  width: 180px;
}

.w-220 {
  width: 220px;
}
</style>
